package com.ruoyi.common.utils.sync;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.http.NetUtils;
import com.ruoyi.common.utils.sign.Base64;
import okhttp3.Credentials;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Map;

@Service
public class MdmProtocol {
    private static final Logger LOGGER = LoggerFactory.getLogger(MdmProtocol.class);
    @Value("${SOA.systems.mdm.url}")
    private String mdm_url;

    @Value("${SOA.username}")
    private String SOAUsername;

    @Value("${SOA.password}")
    private String SOAPassword;

    @Value("#{${SOA.systems.mdm.operations}}")
    private Map operations;

    public JSONObject getMDMData(JSONObject json, String lastUpdateDate, String currentTime)throws Exception {
        long start = System.currentTimeMillis();
        JSONObject param = new JSONObject();
        param.put("applicationCode", "wfcenter");
        param.put("auth", "CC");
        param.put("batch", json.getString("batch"));
        param.put("ifaceCode", json.getString("ifaceCode"));
        param.put("requestID", json.getString("requestID"));
        String reqUrl = mdm_url + "/" + operations.get("getPubIntfApi");
        JSONObject requestData = new JSONObject();
        requestData.put("applicationCode", "wfcenter");
        requestData.put("ifaceCode", json.getString("ifaceCode"));
        requestData.put("startTime", lastUpdateDate);
        requestData.put("endTime", currentTime);
        requestData.put("pageNumber", json.getInteger("pageNumber"));
        requestData.put("batch", json.getString("batch"));
        requestData.put("batchHistory", json.getString("batchHistory"));

        param.put("requestData", Base64.encode(requestData.toJSONString().getBytes(StandardCharsets.UTF_8)));
        String credential = Credentials.basic(SOAUsername, SOAPassword);
        String result = "";
        try {
            result = NetUtils.postBody(reqUrl, param.toJSONString(), credential);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject resturn1 = JSONObject.parseObject(result);
        String return1DataStr = resturn1.getString("data");
        JSONObject return1Data = JSONObject.parseObject(new String(Base64.decode(return1DataStr),StandardCharsets.UTF_8));
        long end = System.currentTimeMillis();
        LOGGER.info("单次接口耗时：" + (end - start) / 1000);
        return return1Data;
    }
}
